package vn.com.vega.chacha.v2.fragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.ActivityBase;
import vn.com.vega.chacha.v2.Appinstant;
import vn.com.vega.chacha.v2.MainScreen;
import vn.com.vega.chacha.v2.player.PlayerService;
import vn.com.vega.music.clientserver.JsonSong;
import vn.com.vega.music.utils.Const;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.utils.VegaLog;
import vn.com.vega.music.view.adapter.SongListAdapter;
import vn.com.vega.music.view.adapter.base.AutoLoadingAdapter;
import vn.com.vega.music.view.adapter.base.AutoLoadingListener;
import vn.com.vega.music.view.custom.LoadingView;
import vn.com.vega.music.view.custom.LoadingView.RetryListener;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

public class ListFeatureSongFragment extends Fragment implements
		AutoLoadingListener, Const {
	private MainScreen mMainScreen;
	private Appinstant mApp;
	private SongListAdapter mAdapter;
	private ListView mListSong;
	// private RelativeLayout mLayoutLoading;
	// private ProgressBar mLoadingbar;
	// private TextView mLoadingText;
	// private Button mRetryBtn;
	private LoadingView mLoadingView;
	private LoadSongFeature mLoader;
	private View mHeaderSongList;
	private TextView mPlayAllSong;
	private TextView mSelectSongToPlay;

	public static Fragment newInstance() {
		ListFeatureSongFragment fragment = new ListFeatureSongFragment();
		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View root = inflater.inflate(R.layout.list_song_feature, null);
		mListSong = (ListView) root.findViewById(R.id.lv_list_song);
		// mLayoutLoading = (RelativeLayout) root
		// .findViewById(R.id.view_feature_loading);
		mHeaderSongList = root.findViewById(R.id.layout_header_list_song);
		mHeaderSongList.setVisibility(View.VISIBLE);
		mPlayAllSong = (TextView) mHeaderSongList
				.findViewById(R.id.tv_play_all_song);
		mSelectSongToPlay = (TextView) mHeaderSongList
				.findViewById(R.id.tv_select_song_play);

		// mLoadingbar = (ProgressBar) root
		// .findViewById(R.id.feature_list_progress);
		// mLoadingText = (TextView) root.findViewById(R.id.feature_help_label);
		// mRetryBtn = (Button) root.findViewById(R.id.feature_help_btn);
		// mRetryBtn.setOnClickListener(retryClickListener);
		mLoadingView = (LoadingView) root
				.findViewById(R.id.loadingView_loading_list_feature);
		mLoadingView.setRetryListener(retryListener);
		mPlayAllSong.setOnClickListener(playAllClickListener);
		mSelectSongToPlay.setOnClickListener(selectSongPlayListener);
		return root;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mMainScreen = (MainScreen) getActivity();
		mApp = (Appinstant) mMainScreen.getApplicationContext();
		// if (mApp.listSongFeature.size() > 0) {
		setAdapter();
		// }
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(PlayerService.PLAYSTATE_CHANGED);
		mMainScreen.registerReceiver(receiver, intentFilter);
	}

	private void setAdapter() {
		mAdapter = new SongListAdapter(mMainScreen, mApp.listSongFeature,
				false, ListFeatureSongFragment.class.getName());
		mListSong.setAdapter(new AutoLoadingAdapter(mAdapter, this));
		// mListSong.setOnItemClickListener(onSongClickListener);
	}

	@Override
	public Activity getContext() {
		// TODO Auto-generated method stub
		return mMainScreen;
	}

	@Override
	public List<Object> getMoreData() {
		// TODO Auto-generated method stub
		if (mAdapter.getCount() >= LIST_ITEM_LIMIT) {
			return null;
		}
		List<Object> result = new ArrayList<Object>();
		JsonSong songJson = JsonSong.loadTopSongList(mAdapter.getCount());
		if (songJson.isSuccess()) {
			result.addAll(songJson.songs);
			mApp.listSongFeature.addAll(songJson.songs);
		}
		return result;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		VegaLog.e(SongListAdapter.class.getName(), "Resume list feature song");
		if (mAdapter.getCount() == 0) {
			loadListVideoFeature();
		} else {
			showListSong();
		}
	}

	private void loadListVideoFeature() {
		if (mLoader != null && mLoader.getStatus() == Status.RUNNING) {
			showLoading();
		} else {
			if (mLoader != null) {
				mLoader.cancel(true);
			}
			mLoader = new LoadSongFeature(this);
			mLoader.execute();
		}
	}

	private void showLoading() {
		mListSong.setVisibility(View.GONE);
		mLoadingView.startLoading();
	}

	private void showListSong() {
		if (mAdapter.getCount() == 0) {
			mListSong.setVisibility(View.GONE);
			mLoadingView.loadingFinish(false,
					"Danh sách bài hát chọn lọc trống!");
		} else {
			mLoadingView.loadingFinish(true, null);
			mListSong.setVisibility(View.VISIBLE);
		}
	}

	RetryListener retryListener = new RetryListener() {

		@Override
		public void onRetry() {
			// TODO Auto-generated method stub
			loadListVideoFeature();
		}
	};

	View.OnClickListener retryClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			loadListVideoFeature();
		}
	};

	View.OnClickListener playAllClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			// openSongAtPosition(0);
			if (mAdapter != null && mAdapter.getCount() > 0) {
				mAdapter.playAllSong("Feature song");
			}
//			mMainScreen.trackEvent(eventCategory, eventAction, eventLabel, eventValue);
		}
	};

	View.OnClickListener selectSongPlayListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			// TODO: do some thing here
			if (mAdapter != null && mAdapter.getCount() > 0) {
				mAdapter.selectSongPlay("Danh sách bài hát chọn lọc");
			}
		}
	};

	// AdapterView.OnItemClickListener onSongClickListener = new
	// AdapterView.OnItemClickListener() {
	//
	// @Override
	// public void onItemClick(AdapterView<?> parent, View view, int position,
	// long id) {
	// // TODO Auto-generated method stub
	// VegaLog.e(ListFeatureSongFragment.class.getName(),
	// "Clicked at item " + position);
	// openSongAtPosition(position);
	// }
	// };

	// private void openSongAtPosition(int position) {
	// List<Song> list = new ArrayList<Song>();
	// for (int i = 0; i < mApp.listSongFeature.size(); i++) {
	// list.add((Song) mApp.listSongFeature.get(i));
	// }
	// mMainScreen.openListSong(list, position);
	// mAdapter.setCurrentPlay(list.get(position));
	// }

	static class LoadSongFeature extends AsyncTask<Void, Void, Void> {
		WeakReference<ListFeatureSongFragment> listSongFragmentRfc;

		public LoadSongFeature(ListFeatureSongFragment base) {
			listSongFragmentRfc = new WeakReference<ListFeatureSongFragment>(
					base);
		}

		private boolean checkActIsLive() {
			ListFeatureSongFragment fragment = listSongFragmentRfc.get();
			if (fragment == null) {
				return false;
			}
			if (fragment.mMainScreen instanceof ActivityBase) {
				if ((fragment.mMainScreen).isDestroy) {
					return false;
				}
			}
			return true;
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (!checkActIsLive()) {
				return null;
			}
			ListFeatureSongFragment fragment = listSongFragmentRfc.get();
			JsonSong songJson = JsonSong.loadTopSongList(0);
			if (songJson.isSuccess()) {
				fragment.mApp.listSongFeature.clear();
				fragment.mApp.listSongFeature.addAll(songJson.songs);
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			if (isCancelled() || !checkActIsLive()) {
				return;
			}

			ListFeatureSongFragment fragment = listSongFragmentRfc.get();
			fragment.setAdapter();
			fragment.showListSong();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			if (!checkActIsLive()) {
				return;
			}
			ListFeatureSongFragment fragment = listSongFragmentRfc.get();
			fragment.showLoading();
		}
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (PlayerService.PLAYSTATE_CHANGED.equalsIgnoreCase(action)) {
				if (mAdapter != null && mAdapter.getCount() > 0) {
					mAdapter.setCurrentPlay(Util.getCurrentSongPlay());
				}
			}
		}
	};

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		mMainScreen.unregisterReceiver(receiver);
		super.onDestroy();
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		mMainScreen.trackPageView("Danh sách bài hát chọn lọc");
	}
}
